import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    component: () =>
      import(/* webpackChunkName: "Login" */ "../components/Login.vue"),
  },
  {
    path: "/home",
    component: () =>
      import(/* webpackChunkName: "Home */ "../components/Home.vue"),
    redirect: "/welcome",
    children: [
      {
        path: "/welcome",
        component: () =>
          import(/* webpackChunkName: "Welcome */ "../components/Welcome.vue"),
      },
      {
        path: "/users",
        component: () =>
          import(/* webpackChunkName: "Users" */ "../components/user/User.vue"),
      },
      {
        path: "/rights",
        component: () =>
          import(
            /* webpackChunkName: "Rights" */ "../components/power/Rights.vue"
          ),
      },
      {
        path: "/roles",
        component: () =>
          import(
            /* webpackChunkName: "Roles" */ "../components/power/Roles.vue"
          ),
      },
      {
        path: "/goods",
        component: () =>
          import(
            /* webpackChunkName: "Goods" */ "../components/commodity/Goods.vue"
          ),
      },
      {
        path: "/categories",
        component: () =>
          import(
            /* webpackChunkName: "Categories" */ "../components/commodity/Categories.vue"
          ),
      },
      {
        path: "/params",
        component: () =>
          import(
            /* webpackChunkName: "Params" */ "../components/commodity/Params.vue"
          ),
      },
      {
        path: "/goods/add",
        component: () =>
          import(
            /* webpackChunkName: "Add" */ "../components/commodity/Add.vue"
          ),
      },
      {
        path: "/reports",
        component: () =>
          import(
            /* webpackChunkName: "Reports" */ "../components/report/Reports.vue"
          ),
      },
      {
        path: "/orders",
        component: () =>
          import(
            /* webpackChunkName: "Orders" */ "../components/order/Orders.vue"
          ),
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

// 为路由对象,添加beforEach导航守卫
router.beforeEach((to, from, next) => {
  // to  将要访问的路径  from  代表从那个路径中跳转过来  next 放行
  if (to.path === "/login") return next();
  // 获取token
  const tokenStr = window.sessionStorage.getItem("token");
  // 如果token不存在  强制跳转到登录页面
  if (!tokenStr) return next("/login");
  next();
});

export default router;
